const puppeteer = require('puppeteer');
const axios = require('axios');
const _ = require('lodash');
const querystring = require('querystring');

// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';

const sleep = function(time) {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve();
    }, time);
  });
};

const {item: oldQuestion} = require('./questions');

const test = async () => {

  const defaultViewport = {
    deviceScaleFactor: 1,
    hasTouch: false,
    height: 1024,
    isLandscape: false,
    isMobile: false,
    width: 1280,
  };

  const browser = await puppeteer.launch({
    args: [
      // '--disable-background-networking',
      // '--disable-default-apps',
      // '--disable-extensions-except=/home/liusen/WebStormWorkSpace/jd-task/extension/',
      // '--load-extension=/home/liusen/WebStormWorkSpace/jd-task/extension/',
      '--disable-sync',
      '--disable-translate',
      // '--hide-scrollbars',
      '--metrics-recording-only',
      '--mute-audio',
      '--no-first-run',
      '--safebrowsing-disable-auto-update',
      // '--ignore-certificate-errors',
      // '--ignore-certificate-errors-spki-list',
      '--user-data-dir=/tmp',
      '--remote-debugging-port=9222',
      '--remote-debugging-address=0.0.0.0',
    ],
    executablePath: '/usr/bin/google-chrome-stable',
    headless: true,
  });

  const pages = await browser.pages();
  const page = pages[0];
  await page.setViewport(defaultViewport);
  await page.goto(
    'http://www.tjjw.gov.cn/index.php?m=actwj&c=h5&subject_id=40');
  // p = page.waitForNavigation({waitUntil: 'networkidle0'});
  await page.click('div.btn-start');

  console.log(`start`);

  const questions = await page.evaluate(() => {
    return $('.inner div.item').map(function() {
      return {
        questionId: $(this).attr('data-id'),
        questionContent: $(this).find('.item-title').
          html().
          replace(/<span>[\d]+.<\/span>/, '').
          replace(/[\n]/, ' ').
          replace(/ /g, ''),
      };
    }).toArray();
    // return Array.prototype.slice.apply(
    //   document.querySelectorAll('.inner div.item')).
    //   map(x => x.getAttribute('data-id'));
  });
  // console.log(`questions=${questions}`);

  const cookies = await page.cookies();

  cookiesStr = _.join(cookies.map(x => `${x.name}=${x.value}`),
    '; ');

  console.log(`cookiesStr=${cookiesStr}`);

  console.log(
    `questions = ${JSON.stringify(_.map(questions, x => x.questionId))}`);

  for (const question of questions) {
    if (_.findIndex(oldQuestion, x => question.questionId === x.questionId) === -1) {

      const {questionId, questionContent} = question;
      console.log(`questionId:${questionId}`);
      console.log(`questionId:${JSON.stringify(question)}`);
      const {data: itemRes} = await axios({
        method: 'post',
        url: 'http://www.tjjw.gov.cn/index.php?m=actwj&c=h5&a=check',
        headers: {
          'Cookie': cookiesStr,
          'Host': 'www.tjjw.gov.cn',
          'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
          'Origin': 'http://www.tjjw.gov.cn',
          'Referer': 'http://www.tjjw.gov.cn/index.php?m=actwj&c=h5&subject_id=40',
          'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
        },
        data: querystring.stringify({
          subject_id: 40,
          item_id: questionId,
          answer: 'A,B,C,D,E,F',
        }),
        responseType: 'json',
      });
      console.log(`itemRes:${JSON.stringify(itemRes)}`);
      // os.exit();
      questionRes = {
        questionId,
        questionContent,
        questionRes: itemRes.suggest,
      };
      if (_.findIndex(oldQuestion, x => _.isEqual(x, questionRes)) === -1) {
        oldQuestion.push(questionRes);
      }

    }
  }

  console.log(`-----------`);
  console.log(`oldQuestion length = ${oldQuestion.length}`);
  console.log(`-----------`);

  require('fs').
    writeFileSync('./questions.json',
      JSON.stringify({
        item: _.sortBy(oldQuestion, [
          function(o) {
            return o.questionId;
          }]),
      }, null, 2));

  // await sleep(100000 * 1000);
  await browser.close();
  // await sleep(30 * 1000);

};

test().then(() => {
}).catch(err => {
  console.log(err);
});

setInterval(function() {
  test().then(() => {
  }).catch(err => {
    console.log(err);
  });
}, 60 * 1000);

